import { uniqBy } from "lodash-es";
import { assign, once } from "underscore";
import { ActionContext, ActionTree } from "vuex";
import { IID, Iobj, asyncgetmynotice, asyncselecmyuserquestion, asyncselectarticle, asyncselectdistinctuserquestion, asyncselectlabel, asyncselectquestion, asyncselectquestionbank, asyncselectquestionlabel, asyncselectteams, asyncselectuser, asyncselectuservip, asyncteamselectactivitys, online, selecteamtteams } from '../../api';

import { Istate } from "../../interface";
import Study from '../../mysql_interface/studycodemodel';
import * as types from './mutation-types';

export type IAction = ActionTree<Istate, Istate>

const actions: IAction = {
  async actiononline({ commit, state }) {
    try {
      const data = await online()
      // const n = await asyncselectuservip({ userid: data.ID })
      // saas 必须有teamid
      // if (!data.teamid) {
      //   console.error("actiononline data.teamid is", data.teamid)
      //   // 没有团队也需要设置用户信息、不然码客行会异常
      //   commit(types.SET_U, data)
      //   return false
      // }
      // data.uservip = n.rows
      commit(types.SET_U, data)
      state.socket.emit('inteamid', { userid: data.ID, teamid: data.teamid })
      return true
    } catch (e: any) {
      console.error("actiononline error", e)
      commit(types.SET_U, undefined)
      return false
    }
  },
  async actionteam({ commit, state }, body?: any) {
    try {
      const data = await selecteamtteams()
      const n = data.rows.map(e => e.name)
      if (n.length) {
        window._teams_ = n.join(',')
        window._teamids_ = data.rows.map(e => e.ID).join(',')
        window._teamidarr_ = data.rows.map(e => e.ID)
      }
      const user = state.user
      if (user?.remarks === '销售助教') {
        if (body) delete body['userid']
        body.isadmin = 0
        const d = await asyncselectteams(body)
        for (const f of d.rows) {
          if (!data.rows.find(e => e.ID === f.ID)) {
            data.rows.push(f)
          }
        }
        commit(types.SET_TEAM, data)
      } else {
        commit(types.SET_TEAM, data)
      }
    } catch (e: any) {
      commit(types.SET_TEAM, null)
    }
  },
  // 切换团队ID
  async changeTeamId({ commit, state }, teamID: number) {
    try {
      const data = { ...state.user, teamid: teamID }
      commit(types.SET_U, data)
    } catch (e: any) {
      console.error("changeTeamId error", e)
      commit(types.SET_U, undefined)
    }
  },

  async actionusers({ commit }, body?: Iobj<Study.Iuser>) {
    try {
      const data = await asyncselectuser(body)
      commit(types.SET_USERS, data)
    } catch (e: any) {
      commit(types.SET_USERS, null)
    }
  },
  async actionactivity({ commit }, body?: Iobj<Study.Iactivity>) {
    try {
      // 获取本团队的比赛
      const data = await asyncteamselectactivitys(body)
      // const data = await asyncselectactivity(body)
      commit(types.SET_ACTIVITY, data)
    } catch (e: any) {
      commit(types.SET_ACTIVITY, null)
    }
  },
  async actionlabel({ commit }, body?: Iobj<Study.ILabel>) {
    try {
      const data = await asyncselectlabel(body)
      commit(types.SET_LABEL, data)
    } catch (e: any) {
      commit(types.SET_LABEL, null)
    }
  },
  async actionarticle({ commit }, body: Iobj<Study.Iarticle> = {}) {
    try {
      body.showtype = ['1', '2']
      const data = await asyncselectarticle(body)
      commit(types.SET_ARTICLE, data)
    } catch (e: any) {
      commit(types.SET_ARTICLE, null)
    }
  },
  async actionquestion({ commit }, body: Iobj<Study.Iquestion> = {}) {
    if (!body._sortable) {
      body._sortable = 'ASC'
    }
    if (!body.type) {
      body.type = '代码'
    }
    try {
      const data = await asyncselectquestion(body)
      commit(types.SET_QUESTION, data)
    } catch (e: any) {
      commit(types.SET_QUESTION, null)
    }
  },
  async actionquestionbank({ commit }, body?: Iobj<Study.Iquestionbank>) {
    try {
      const data = await asyncselectquestionbank(body)
      try {
        const questions = data.rows.map(t => t.questionquestionbank?.map(f => f.questionid)).flat()
        const questionlabels = await asyncselectquestionlabel({
          questionid: questions,
        })
        const rows = data.rows.map(e => {
          const { questionquestionbank } = e
          const questionlabel = questionquestionbank?.map(t => {
            const { questionid } = t
            return questionlabels.rows.filter(t => t.questionid === questionid)
          }).flat() || []
          return assign(e, { questionlabel: uniqBy(questionlabel, e => e.labelid) })
        })
        commit(types.SET_QUESTIONBANK, assign(data, { rows }))
      } catch (e) {
        commit(types.SET_QUESTIONBANK, data)
      }

    } catch (e: any) {
      commit(types.SET_QUESTIONBANK, null)
    }
  },
  async actionmyuserquestion({ commit }, body?: IID) {
    try {
      const data = await asyncselecmyuserquestion(body)
      commit(types.SET_LABEL, data)
    } catch (e: any) {
      commit(types.SET_LABEL, null)
    }
  },
  async actionMyPractiseQuestion({ commit }, body?: Iobj<Study.Iuserquestion> | undefined) {
    try {
      const { rows, count } = await asyncselectdistinctuserquestion(body)
      commit(types.SET_MY_PRACTISE_QUESTION, rows)
    } catch (e: any) {
      commit(types.SET_MY_PRACTISE_QUESTION, null)
    }
  },

  async actionmynotice({ commit }, body?: Iobj<Study.Iusernotice>) {
    try {
      const data = await asyncgetmynotice(body)
      commit(types.SET_NOTICE, data)
    } catch (e: any) {
      commit(types.SET_NOTICE, null)
    }
  },
  async actiontime(action) {
    gettime(action)
  }
}

const gettime = once((action: ActionContext<Istate, Istate>) => {
  action.state.socket?.on('time', e => {
    action.commit('time', Number(e))
  })
})

export default actions
